use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::Json,
};
use fluviox_shared::models::*;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::sync::Arc;
use uuid::Uuid;
use crate::AppState;

#[derive(Debug, Deserialize)]
pub struct CreateConnectorRequest {
    pub name: String,
    pub connector_type: ConnectorType,
    pub specification: ConnectorSpec,
    pub configuration: std::collections::HashMap<String, serde_json::Value>,
}

#[derive(Debug, Serialize)]
pub struct ConnectorResponse {
    pub id: Uuid,
    pub name: String,
    pub connector_type: ConnectorType,
    pub status: ConnectorStatus,
    pub created_at: chrono::DateTime<chrono::Utc>,
}

pub async fn list_connectors(
    State(state): State<Arc<AppState>>,
) -> Result<Json<Vec<ConnectorResponse>>, StatusCode> {
    match state.db.list_connectors().await {
        Ok(connectors) => {
            let response: Vec<ConnectorResponse> = connectors
                .into_iter()
                .map(|c| ConnectorResponse {
                    id: c.id,
                    name: c.name,
                    connector_type: c.connector_type,
                    status: c.status,
                    created_at: c.created_at,
                })
                .collect();
            Ok(Json(response))
        }
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

pub async fn create_connector(
    State(state): State<Arc<AppState>>,
    Json(request): Json<CreateConnectorRequest>,
) -> Result<Json<ConnectorResponse>, StatusCode> {
    let connector = Connector {
        id: Uuid::new_v4(),
        name: request.name,
        connector_type: request.connector_type,
        specification: request.specification,
        configuration: request.configuration,
        status: ConnectorStatus::Inactive,
        created_at: chrono::Utc::now(),
        updated_at: chrono::Utc::now(),
    };

    match state.db.create_connector(&connector).await {
        Ok(_) => Ok(Json(ConnectorResponse {
            id: connector.id,
            name: connector.name,
            connector_type: connector.connector_type,
            status: connector.status,
            created_at: connector.created_at,
        })),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

pub async fn get_connector(
    State(state): State<Arc<AppState>>,
    Path(id): Path<Uuid>,
) -> Result<Json<Connector>, StatusCode> {
    match state.db.get_connector(id).await {
        Ok(Some(connector)) => Ok(Json(connector)),
        Ok(None) => Err(StatusCode::NOT_FOUND),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

pub async fn update_connector(
    State(_state): State<Arc<AppState>>,
    Path(_id): Path<Uuid>,
    Json(_request): Json<Value>,
) -> Result<Json<Value>, StatusCode> {
    // TODO: 实现连接器更新逻辑
    Ok(Json(json!({"message": "连接器更新功能待实现"})))
}

pub async fn delete_connector(
    State(_state): State<Arc<AppState>>,
    Path(_id): Path<Uuid>,
) -> Result<Json<Value>, StatusCode> {
    // TODO: 实现连接器删除逻辑
    Ok(Json(json!({"message": "连接器删除功能待实现"})))
}

pub async fn test_connector(
    State(_state): State<Arc<AppState>>,
    Path(_id): Path<Uuid>,
) -> Result<Json<Value>, StatusCode> {
    // TODO: 实现连接器测试逻辑
    Ok(Json(json!({
        "status": "success",
        "message": "连接器测试通过"
    })))
}
